package swordoffer.offer13;

public class DFS {
    public int movingCount(int m, int n, int k) {
        if (k == 0) {
            return 1;
        }
        boolean[][] visited = new boolean[m][n];
        return dfs(m, n, k, 0, 0, visited);
    }

    public int dfs(int m, int n, int k, int i, int j, boolean[][] visited) {
        if (i >= m || j >= n  || bitSum(i) + bitSum(j) > k || visited[i][j]) {
            return 0;
        }
        visited[i][j] = true;
        // 由于从 (0,0) 出发，每一个只需要向下或向右即可全部访问到，而无需四个方向都走。
        return 1 + dfs(m, n, k, i + 1, j, visited) + dfs(m, n, k, i, j + 1, visited);
    }

    /*
        计算数位之和
     */
    public int bitSum(int num) {
        int sum = 0;
        while (num > 0) {
            sum += num % 10;
            num /= 10;
        }
        return sum;
    }
}
